package cn.xu.framework.common.utils;


import java.util.concurrent.atomic.AtomicLong;

/**
 * @author Clark Xu<clark2021@qq.com>
 * @date 2024/8/7
 */
public class SnowflakeIDGenerator {

    private final long workerId;
    private final long datacenterId;
    private final long sequence = 0L;
    private final long twepoch = 1577808000000L; // 时间基点，例如：2020-01-01 00:00:00 UTC

    private final AtomicLong workerIdBits = new AtomicLong(0L);
    private final AtomicLong datacenterIdBits = new AtomicLong(0L);
    private final AtomicLong sequenceBits = new AtomicLong(0L);

    private final long workerIdShift = 5L;
    private final long datacenterIdShift = 10L;
    private final long timestampLeftShift = 22L;
    private final long sequenceMask = 4095L;

    private long lastTimestamp = -1L;

    //确保所有节点上的workerId和datacenterId配置正确且不重复。
    public SnowflakeIDGenerator(long workerId, long datacenterId) {
        if (workerId > 31 || workerId < 0) {
            throw new IllegalArgumentException("Worker ID must be between 0 and 31");
        }
        if (datacenterId > 31 || datacenterId < 0) {
            throw new IllegalArgumentException("Datacenter ID must be between 0 and 31");
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    public synchronized long nextId() {
        long timestamp = timeGen();

        // 如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过，这时候应当抛出异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(
                    String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        // 如果是同一时间生成的，则进行毫秒内序列
        if (lastTimestamp == timestamp) {
            sequenceBits.incrementAndGet();
            // 序列号超过限制，阻塞到下一个毫秒，获得新的时间戳
            while (sequenceBits.get() > sequenceMask) {
                timestamp = timeGen();
                if (timestamp != lastTimestamp) {
                    sequenceBits.set(0);
                    break;
                }
            }
        } else { // 时间戳改变，毫秒内序列重置
            sequenceBits.set(0);
        }

        // 上次生成ID的时间截
        lastTimestamp = timestamp;

        // 移位并通过或运算拼到一起组成64位的ID
        return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequenceBits.get();
    }

    protected long timeGen() {
        return System.currentTimeMillis();
    }

    public static void main(String[] args) {
        SnowflakeIDGenerator generator = new SnowflakeIDGenerator(1, 1);
        for (int i = 0; i < 10; i++) {
            System.out.println(generator.nextId());
        }
        System.out.println("-----------------");
        generator = new SnowflakeIDGenerator(2, 2);
        for (int i = 0; i < 10; i++) {
            System.out.println(generator.nextId());
        }
    }
}